package cn.com.zhangwoo.microstar.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import cn.com.microstar.activity.R;
import cn.com.zhangwoo.microstar.adapter.ShopcartExpandableListViewAdapter;
import cn.com.zhangwoo.microstar.entity.GroupInfo;
import cn.com.zhangwoo.microstar.entity.ProductInfo;
import cn.com.zhangwoo.microstar.http.ApplicationController;
import cn.com.zhangwoo.microstar.http.NetUtils;
import cn.com.zhangwoo.microstar.http.NormalPostRequest;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
/***
 * 购物车
 */
public class ShoppingCartFragment extends Fragment implements OnClickListener,cn.com.zhangwoo.microstar.adapter.ShopcartExpandableListViewAdapter.CheckInterface, cn.com.zhangwoo.microstar.adapter.ShopcartExpandableListViewAdapter.ModifyCountInterface{
	private ExpandableListView exListView;
	private CheckBox cb_check_all;
	private TextView tv_total_price;
	private TextView tv_delete;
	private TextView tv_go_to_pay;
	private Context context;
	private double totalPrice = 0.00;// 购买的商品总价
	private int totalCount = 0;// 购买的商品总数量
	View view;
	private TextView mTextView,TotalPrice;
	private ImageView mImageView;
	private ShopcartExpandableListViewAdapter selva;
	private List<GroupInfo> groups = new ArrayList<GroupInfo>();// 组元素数据列表
	private Map<String, List<ProductInfo>> children = new HashMap<String, List<ProductInfo>>();// 子元素数据列表
	//private Map<String, List<ShoppingCartInfo>> childcart = new HashMap<String, List<ShoppingCartInfo>>();// 子元素数据列表
	//List<ShoppingCartInfo.Data>  listdata;
	
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		return inflater.inflate(R.layout.fragment_shoppingcart, container, false);
	}
	
	
	@Override
	public void onActivityCreated( Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		context=getActivity();
		view=getView();
		//listdata=new ArrayList<ShoppingCartInfo.Data>();
		initView();
		if (!NetUtils.isNetworkAvailable(getActivity())) {
			Toast.makeText(getActivity(), "网络未连接", 1).show();
		}
	}
	
	/***
	 * 购买刷新
	 */
	@Override
	public void onResume() {
	// TODO Auto-generated method stub
	super.onResume();
	/* if(UtilDB.ISLOGIN())
	{
		Toast.makeText(getActivity(), "请登录", 1).show();
		return;
	}
	else
	{
		 getPostGridView(IUtilDBRequest.BASE_URL,UtilDB.SHOWSHOPPINGCART(UtilDB.LOGINUID(), "0"),1);
	}*/
	}
	
	
	private void initView() {
		mImageView=(ImageView) view.findViewById(R.id.signin_actionbar_title_img);
		mImageView.setVisibility(View.GONE);
        mTextView=(TextView)view.findViewById(R.id.signin_actionbar_title_text);
        mTextView.setText("购物车");
        exListView = (ExpandableListView) view.findViewById(R.id.exListView);
		cb_check_all = (CheckBox)view.findViewById(R.id.all_chekbox);
		tv_total_price = (TextView) view.findViewById(R.id.tv_total_price);
		tv_delete = (TextView)view.findViewById(R.id.tv_delete);
		tv_go_to_pay = (TextView)view.findViewById(R.id.tv_go_to_pay);
		cb_check_all.setOnClickListener(this);
		tv_delete.setOnClickListener(this);
		tv_go_to_pay.setOnClickListener(this);
		virtualData();
		initEvents();
       
	}
	private void initEvents()
	{
		selva = new ShopcartExpandableListViewAdapter(groups, children, getActivity());
		selva.setCheckInterface(this);// 关键步骤1,设置复选框接口
		selva.setModifyCountInterface(this);// 关键步骤2,设置数量增减接口
		exListView.setAdapter(selva);

		for (int i = 0; i < selva.getGroupCount(); i++)
		{
			exListView.expandGroup(i);// 关键步骤3,初始化时，将ExpandableListView以展开的方式呈现
		}

		
	}
	
	/**
	 * 模拟数据<br>
	 * 遵循适配器的数据列表填充原则，组元素被放在一个List中，对应的组元素下辖的子元素被放在Map中，<br>
	 * 其键是组元素的Id(通常是一个唯一指定组元素身份的值)
	 */
	private void virtualData()//相同的为一类
	{

		for (int i = 0; i < 5; i++)
		{
			
			groups.add(new GroupInfo(i + "", "商品"+i));
			List<ProductInfo> products = new ArrayList<ProductInfo>();
			for (int j = 0; j <1; j++)
			{
				products.add(new ProductInfo(0 + "", "商品", "http://hiphotos.baidu.com/baidu/pic/item/bd3eb13533fa828b48da6aabfd1f4134960a5af9.jpg", "name", "12", 1));
			}
			children.put(groups.get(i).getId(), products);// 将组元素的一个唯一值，这里取Id，作为子元素List的Key
		}
		
	}		
	
	
	@Override
	public void onClick(View v)
	{
		AlertDialog alert;
		switch (v.getId())
		{
		case R.id.all_chekbox:
			doCheckAll();
			break;
		case R.id.tv_go_to_pay:
			if (totalCount == 0)
			{
				Toast.makeText(context, "请选择要支付的商品", Toast.LENGTH_LONG).show();
				return;
			}
			alert = new AlertDialog.Builder(context).create();
			alert.setTitle("操作提示");
			alert.setMessage("总计:\n" + totalCount + "种商品\n" + totalPrice + "元");
			alert.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener()
			{
				@Override
				public void onClick(DialogInterface dialog, int which)
				{
					return;
				}
			});
			alert.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener()
			{
				@Override
				public void onClick(DialogInterface dialog, int which)
				{
					return;
				}
			});
			alert.show();
			break;
		case R.id.tv_delete:
			if (totalCount == 0)
			{
				Toast.makeText(context, "请选择要移除的商品", Toast.LENGTH_LONG).show();
				return;
			}
			alert = new AlertDialog.Builder(context).create();
			alert.setTitle("操作提示");
			alert.setMessage("您确定要将这些商品从购物车中移除吗？");
			alert.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener()
			{
				@Override
				public void onClick(DialogInterface dialog, int which)
				{
					return;
				}
			});
			alert.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener()
			{
				@Override
				public void onClick(DialogInterface dialog, int which)
				{
					//doDelete();
					Toast.makeText(context, "移除成功", Toast.LENGTH_LONG).show();
				}
			});
			alert.show();
			break;
		}
	}

	/**
	 * 删除操作<br>
	 * 1.不要边遍历边删除，容易出现数组越界的情况<br>
	 * 2.现将要删除的对象放进相应的列表容器中，待遍历完后，以removeAll的方式进行删除
	 */
	protected void doDelete()
	{
		List<GroupInfo> toBeDeleteGroups = new ArrayList<GroupInfo>();// 待删除的组元素列表
		for (int i = 0; i < groups.size(); i++)
		{
			GroupInfo group = groups.get(i);
			if (group.isChoosed())
			{
				toBeDeleteGroups.add(group);
			}
			List<ProductInfo> toBeDeleteProducts = new ArrayList<ProductInfo>();// 待删除的子元素列表
			List<ProductInfo> childs = children.get(group.getId());
			for (int j = 0; j < childs.size(); j++)
			{
				if (childs.get(j).isChoosed())
				{
					toBeDeleteProducts.add(childs.get(j));
				}
			}
			childs.removeAll(toBeDeleteProducts);
		}
		groups.removeAll(toBeDeleteGroups);
		selva.notifyDataSetChanged();
		calculate();
	}

	@Override
	public void doIncrease(int groupPosition, int childPosition, View showCountView, boolean isChecked)
	{

		ProductInfo product = (ProductInfo) selva.getChild(groupPosition, childPosition);
		int currentCount = product.getCount();
		currentCount++;
		product.setCount(currentCount);
		((TextView) showCountView).setText(currentCount + "");
		selva.notifyDataSetChanged();
		calculate();
	}

	@Override
	public void doDecrease(int groupPosition, int childPosition, View showCountView, boolean isChecked)
	{

		ProductInfo product = (ProductInfo) selva.getChild(groupPosition, childPosition);
		int currentCount = product.getCount();
		if (currentCount == 1)
			return;
		currentCount--;
		product.setCount(currentCount);
		((TextView) showCountView).setText(currentCount + "");

		selva.notifyDataSetChanged();
		calculate();
	}

	@Override
	public void checkGroup(int groupPosition, boolean isChecked)
	{
		GroupInfo group = groups.get(groupPosition);
		List<ProductInfo> childs = children.get(group.getId());
		for (int i = 0; i < childs.size(); i++)
		{
			childs.get(i).setChoosed(isChecked);
		}
		if (isAllCheck())
			cb_check_all.setChecked(true);
		else
			cb_check_all.setChecked(false);
		selva.notifyDataSetChanged();
		calculate();
	}

	@Override
	public void checkChild(int groupPosition, int childPosiTion, boolean isChecked)
	{
		boolean allChildSameState = true;// 判断改组下面的所有子元素是否是同一种状态
		GroupInfo group = groups.get(groupPosition);
		List<ProductInfo> childs = children.get(group.getId());
		for (int i = 0; i < childs.size(); i++)
		{
			if (childs.get(i).isChoosed() != isChecked)
			{
				allChildSameState = false;
				break;
			}
		}
		if (allChildSameState)
		{
			group.setChoosed(isChecked);// 如果所有子元素状态相同，那么对应的组元素被设为这种统一状态
		} else
		{
			group.setChoosed(false);// 否则，组元素一律设置为未选中状态
		}

		if (isAllCheck())
			cb_check_all.setChecked(true);
		else
			cb_check_all.setChecked(false);
		selva.notifyDataSetChanged();
		calculate();
	}

	private boolean isAllCheck()
	{

		for (GroupInfo group : groups)
		{
			if (!group.isChoosed())
				return false;

		}

		return true;
	}

	/** 全选与反选 */
	private void doCheckAll()
	{
		for (int i = 0; i < groups.size(); i++)
		{
			groups.get(i).setChoosed(cb_check_all.isChecked());
			GroupInfo group = groups.get(i);
			List<ProductInfo> childs = children.get(group.getId());
			for (int j = 0; j < childs.size(); j++)
			{
				childs.get(j).setChoosed(cb_check_all.isChecked());
			}
		}
		selva.notifyDataSetChanged();
		
		
		calculate();///1
	}

	/**
	 * 统计操作<br>
	 * 1.先清空全局计数器<br>
	 * 2.遍历所有子元素，只要是被选中状态的，就进行相关的计算操作<br>
	 * 3.给底部的textView进行数据填充
	 */
	private void calculate()
	{
		totalCount = 0;
		totalPrice = 0.00;
		for (int i = 0; i < groups.size(); i++)
		{
			GroupInfo group = groups.get(i);
			List<ProductInfo> childs = children.get(group.getId());
			for (int j = 0; j < childs.size(); j++)
			{
				ProductInfo product = childs.get(j);
				if (product.isChoosed())
				{
					totalCount++;
					totalPrice +=(Double.valueOf(product.getPrice())* product.getCount());// product.getPrice()* product.getCount()
				}
			}
		}
		tv_total_price.setText("￥" + totalPrice);
		tv_go_to_pay.setText("去支付(" + totalCount + ")");
		
	}
	
	
	
	
	  public void getPostGridView(String url, Map<String, String> map,final int index)
	   	{
		  if (!NetUtils.isNetworkAvailable(getActivity())) {
				return;
			}
	   		  RequestQueue requestQueue =ApplicationController.getHttpQueue();
	   		  Request<JSONObject> request = new NormalPostRequest(url,
	   		    new Response.Listener<JSONObject>() {
	   		        @Override
	   		        public void onResponse(JSONObject response) {
	   		        	if(index==1){
							Gson gson=new Gson();
							/*ShoppingCartInfo m=gson.fromJson(response.toString(), ShoppingCartInfo.class);
							if(m.getData().size()>0)
							{
								listdata=m.getData();
								virtualData();
								initEvents();
							}*/
	   		        	}
	   		        	else if(index==2)
	   		        	{
	   		        		Gson gson=new Gson();
							/*ShoppingCartInfo m=gson.fromJson(response.toString(), ShoppingCartInfo.class);
							if(m.getData().size()>0)
							{
								
							}*/
	   		        	}
	   		        
	   		        }
	   		    	}, new Response.ErrorListener() {
	   		        @Override
	   		        public void onErrorResponse(VolleyError error) {
	   		        	Toast.makeText(getActivity(), "网络异常", 2)
	   					.show();
	   		        }
	   		    	}, map);
	   		requestQueue.add(request);
	   	}



}
